package cn.broadmax.boot.modules.sys.controller;

import cn.broadmax.boot.constant.ThirdAccountType;
import cn.broadmax.boot.log.SysLog;
import cn.broadmax.boot.modules.sys.entity.SysUserThird;
import cn.broadmax.boot.oauth.OauthLoginProvider;
import cn.broadmax.boot.oauth.OauthLoginResponse;
import cn.broadmax.boot.oauth.OauthLoginSelector;
import cn.broadmax.boot.base.message.SResult;
import cn.broadmax.boot.base.model.LoginUser;
import cn.broadmax.boot.modules.sys.service.ISysUserThirdService;
import cn.broadmax.boot.util.JwtUtils;
import cn.broadmax.boot.util.SAssert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 第三方登陆
 * @author jeff
 * @date 2020/6/25
 */
@Slf4j
@Api(tags = "第三方登陆")
@RestController
@RequestMapping("/thirdLogin")
public class ThirdLoginController {

    @Autowired
    private ISysUserThirdService sysUserThirdService;

    @Autowired
    private OauthLoginSelector oauthLoginSelector;

    @ApiOperation("oauth登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="type", value = "类型; alipay", paramType = "path", dataType = "String"),
            @ApiImplicitParam(name="authCode", value = "授权码", paramType = "query", dataType = "String")
    })
    @SysLog(value = "第三方登陆")
    @PostMapping(value = "/type/{type}")
    public SResult<Object> login(@PathVariable ThirdAccountType type, String authCode, HttpServletRequest request){
        SAssert.notNull(type);
        SAssert.hasText(authCode, "authCode不能为空");

        OauthLoginProvider provider = oauthLoginSelector.get(type);
        SAssert.notNull(provider, "找不到对应oauth实现类");

        OauthLoginResponse response = provider.login(authCode);
        SAssert.notNull(response);

        SysUserThird sysUserThird = sysUserThirdService.login(response);
        SAssert.notNull(sysUserThird);

        LoginUser loginUser = provider.saveUser(sysUserThird.getUserId(), response);

        Map<String, Object> map = new HashMap<>(4);

        Map<String, Object> oauthMap = new HashMap<>(4);
        oauthMap.put("userId", response.getThirdUserId());
        oauthMap.put("accessToken", response.getAccessToken());
        oauthMap.put("refreshToken", response.getRefreshToken());

        map.put("oauth", oauthMap);
        map.put("user", loginUser);
        String token = JwtUtils.generateToken(loginUser);
        map.put("token", token);
        return SResult.ok("", map);
    }

}
